package service

import (
	"fmt"
	"github.com/asaskevich/govalidator"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
	"worklog/models"
	"worklog/utils"
)

// GetUser 获取所有用户
// @Summary 展示用户信息
// @Tags 用户模块
// @Success 200 {string} json["code","message","data"]
// @Router /user [get]
func GetUser(c *gin.Context) {
	data := models.GetUser()
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "success",
		"data":    data,
	})
}

// CreateUser
// @Summary 新增用户
// @Tags 用户模块
// @param name formData string false "用户名"
// @param password formData string false "密码"
// @param repassword formData string false "确认密码"
// @Sources 200 {string} json{"code","message"}
// @Router /user [post]
func CreateUser(c *gin.Context) {
	const (
		errorPasswordMessage   = "input passwd is different"
		errorUserMessageEmpty  = "Username must not be empty"
		errorUserMessageExists = "Username is exists"
		successMessage         = "add user success"
	)
	user := models.User{}
	user.Salt = strconv.FormatInt(time.Now().Unix(), 10)
	user.UserName = c.PostForm("name")
	user.PassWord = c.PostForm("password")
	rePassword := c.PostForm("repassword")
	_, err := govalidator.ValidateStruct(user)
	if err != nil {
		fmt.Println(err)
		return
	}
	if user.UserName == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": errorUserMessageEmpty,
		})
		return
	}
	data := models.FindUserBYUsername(user.UserName)
	if data.UserName != "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": errorUserMessageExists,
		})
		return
	}
	if user.PassWord != rePassword {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  errorPasswordMessage,
		})
	} else {
		user.MD5Password = utils.MD5(user.PassWord, user.Salt)
		err := models.CreateUser(user)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"code": 400,
				"msg":  "mysql error",
			})
		}
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": successMessage,
			"data":    user,
		})
	}
}
